package org.eclipse.moquette.parser.netty;

import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.handler.codec.CorruptedFrameException;
import io.netty.handler.codec.MessageToByteEncoder;
import org.eclipse.moquette.proto.messages.AbstractMessage;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by alex on 15-5-19.
 */
public class MQTTEncoder extends MessageToByteEncoder<AbstractMessage> {

    private Map<Byte, DemuxEncoder> m_encoderMap = new HashMap<Byte, DemuxEncoder>();

    public MQTTEncoder() {
        m_encoderMap.put(AbstractMessage.CONNECT, new ConnectEncoder());
    }

    @Override
    protected void encode(ChannelHandlerContext channelHandlerContext, AbstractMessage message, ByteBuf byteBuf) throws Exception {
        DemuxEncoder encoder = m_encoderMap.get(message.getMessageType());
        if (encoder == null){
            throw new CorruptedFrameException("Can't find any suitable decoder for message type: " + message.getMessageType());
        }
        encoder.encode(channelHandlerContext,message,byteBuf);
    }
}
